import { Request, Response } from 'express';
import { TerminalManager } from '../services/terminalManager';
import { ApiResponse, ErrorCode } from '../types';

const terminalManager = new TerminalManager();

export const createTerminal = async (req: Request, res: Response): Promise<void> => {
  try {
    const { userId, shell, cwd, env, cols, rows } = req.body;
    
    if (!userId) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: 'userId (用户标识) 参数是必填的，请指定唯一的用户标识（如: claude-assistant-1, gpt-bot-2）'
        }
      };
      res.status(400).json(response);
      return;
    }

    if (!cwd) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: 'cwd (工作目录) 参数是必填的，请指定终端的工作目录'
        }
      };
      res.status(400).json(response);
      return;
    }
    
    const session = await terminalManager.createTerminal({
      userId,
      shell,
      cwd,
      env,
      cols,
      rows
    });

    const response: ApiResponse = {
      success: true,
      data: {
        terminalId: session.id,
        userId: session.userId,
        pid: session.pid,
        shell: session.shell,
        cwd: session.cwd,
        created: session.created,
        status: session.status
      },
      message: `✅ 终端创建成功！用户: ${session.userId}, 工作目录: ${session.cwd} - 请确认信息是否正确`
    };

    res.status(201).json(response);
  } catch (error) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'INTERNAL_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error'
      }
    };
    res.status(500).json(response);
  }
};

export const sendInput = async (req: Request, res: Response): Promise<void> => {
  try {
    const { terminalId } = req.params;
    const { userId, input } = req.body;

    if (!userId) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: 'userId is required'
        }
      };
      res.status(400).json(response);
      return;
    }

    if (!input) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: 'Input is required'
        }
      };
      res.status(400).json(response);
      return;
    }

    const terminalInfo = await terminalManager.getTerminalInfo(terminalId, userId);
    await terminalManager.writeToTerminal(terminalId, userId, input);

    const response: ApiResponse = {
      success: true,
      data: {
        message: 'Input sent successfully'
      },
      message: `💡 命令已发送到终端。用户: ${terminalInfo.userId}, 工作目录: ${terminalInfo.cwd} - 请确认信息是否正确`
    };

    res.json(response);
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    let statusCode = 500;
    let errorCode: ErrorCode = 'INTERNAL_ERROR';

    if (errorMessage === 'TERMINAL_NOT_FOUND') {
      statusCode = 404;
      errorCode = 'TERMINAL_NOT_FOUND';
    } else if (errorMessage === 'TERMINAL_INACTIVE') {
      statusCode = 400;
      errorCode = 'TERMINAL_INACTIVE';
    } else if (errorMessage === 'PERMISSION_DENIED') {
      statusCode = 403;
      errorCode = 'PERMISSION_DENIED';
    } else if (errorMessage.includes('WRITE_FAILED')) {
      errorCode = 'WRITE_FAILED';
    }

    const response: ApiResponse = {
      success: false,
      error: {
        code: errorCode,
        message: errorMessage
      }
    };

    res.status(statusCode).json(response);
  }
};

export const readOutput = async (req: Request, res: Response): Promise<void> => {
  try {
    const { terminalId } = req.params;
    const { userId, since, mode, headLines, tailLines, maxLines, clean } = req.query;

    if (!userId) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: 'userId parameter is required'
        }
      };
      res.status(400).json(response);
      return;
    }

    const options = {
      since: since ? parseInt(since as string) : undefined,
      mode: mode as any,
      headLines: headLines ? parseInt(headLines as string) : undefined,
      tailLines: tailLines ? parseInt(tailLines as string) : undefined,
      maxLines: maxLines ? parseInt(maxLines as string) : undefined,
      clean: clean === 'true' || clean === '1'
    };

    const terminalInfo = await terminalManager.getTerminalInfo(terminalId, userId as string);
    const result = await terminalManager.readFromTerminal(terminalId, userId as string, options);

    const response: ApiResponse = {
      success: true,
      data: result,
      message: `📂 正在读取终端输出。用户: ${terminalInfo.userId}, 工作目录: ${terminalInfo.cwd} - 请确认信息是否正确`
    };

    res.json(response);
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    let statusCode = 500;
    let errorCode: ErrorCode = 'INTERNAL_ERROR';

    if (errorMessage === 'TERMINAL_NOT_FOUND') {
      statusCode = 404;
      errorCode = 'TERMINAL_NOT_FOUND';
    } else if (errorMessage === 'PERMISSION_DENIED') {
      statusCode = 403;
      errorCode = 'PERMISSION_DENIED';
    } else if (errorMessage.includes('READ_FAILED')) {
      errorCode = 'READ_FAILED';
    }

    const response: ApiResponse = {
      success: false,
      error: {
        code: errorCode,
        message: errorMessage
      }
    };

    res.status(statusCode).json(response);
  }
};

export const getStats = async (req: Request, res: Response): Promise<void> => {
  try {
    const { terminalId } = req.params;
    const { userId } = req.query;

    if (!userId) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: 'userId parameter is required'
        }
      };
      res.status(400).json(response);
      return;
    }

    const stats = await terminalManager.getTerminalStats(terminalId, userId as string);

    const response: ApiResponse = {
      success: true,
      data: stats
    };

    res.json(response);
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    let statusCode = 500;
    let errorCode: ErrorCode = 'INTERNAL_ERROR';

    if (errorMessage === 'TERMINAL_NOT_FOUND') {
      statusCode = 404;
      errorCode = 'TERMINAL_NOT_FOUND';
    } else if (errorMessage === 'PERMISSION_DENIED') {
      statusCode = 403;
      errorCode = 'PERMISSION_DENIED';
    }

    const response: ApiResponse = {
      success: false,
      error: {
        code: errorCode,
        message: errorMessage
      }
    };

    res.status(statusCode).json(response);
  }
};

export const listTerminals = async (req: Request, res: Response): Promise<void> => {
  try {
    const { userId } = req.query;
    const terminals = await terminalManager.listTerminals(userId as string | undefined);

    const response: ApiResponse = {
      success: true,
      data: {
        terminals,
        count: terminals.length,
        filteredBy: userId ? `user: ${userId}` : 'all users'
      }
    };

    res.json(response);
  } catch (error) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'INTERNAL_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error'
      }
    };

    res.status(500).json(response);
  }
};

export const killTerminal = async (req: Request, res: Response): Promise<void> => {
  try {
    const { terminalId } = req.params;
    const { userId, signal = 'SIGTERM' } = req.body || {};

    if (!userId) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: 'userId is required'
        }
      };
      res.status(400).json(response);
      return;
    }

    await terminalManager.killTerminal(terminalId, userId, signal);

    const response: ApiResponse = {
      success: true,
      data: {
        message: 'Terminal terminated successfully'
      }
    };

    res.json(response);
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    let statusCode = 500;
    let errorCode: ErrorCode = 'INTERNAL_ERROR';

    if (errorMessage === 'TERMINAL_NOT_FOUND') {
      statusCode = 404;
      errorCode = 'TERMINAL_NOT_FOUND';
    } else if (errorMessage === 'PERMISSION_DENIED') {
      statusCode = 403;
      errorCode = 'PERMISSION_DENIED';
    } else if (errorMessage === 'KILL_FAILED') {
      errorCode = 'KILL_FAILED';
    }

    const response: ApiResponse = {
      success: false,
      error: {
        code: errorCode,
        message: errorMessage
      }
    };

    res.status(statusCode).json(response);
  }
};

export const healthCheck = async (_req: Request, res: Response): Promise<void> => {
  try {
    const terminals = await terminalManager.listTerminals();
    const uptime = process.uptime();

    const response: ApiResponse = {
      success: true,
      data: {
        status: 'healthy',
        uptime: Math.floor(uptime),
        activeTerminals: terminals.filter(t => t.status === 'active').length,
        version: '1.0.0'
      }
    };

    res.json(response);
  } catch (error) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'INTERNAL_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error'
      }
    };

    res.status(500).json(response);
  }
};

export const getTerminalManager = (): TerminalManager => {
  return terminalManager;
};
